const https = require("https");
const fs = require("fs");

const Koa = require("koa");
const koaStatic = require("koa-static");
const koaMount = require("koa-mount");

const app = new Koa();
app.use(koaMount("/", koaStatic("./")));

const sslOptions = {
    key: fs.readFileSync("./tls.key"),
    cert: fs.readFileSync("./tls.crt")
};
const server = https.createServer(sslOptions, app.callback());

const io = require("socket.io")(server);

const onlineUsers = new Set();

io.on("connection", socket => {
    socket.join(socket.id);
    onlineUsers.add(socket.id);

    console.log(`${socket.id}: connected`);
    socket.on("disconnect", () => {
        console.log(`${socket.id}: disconnected`);
        onlineUsers.delete(socket.id);
        socket.leave(socket.id);
    });
    
    //sdp 消息的转发
    socket.on('sdp', (data) => {
        // console.log('sdp');
        // console.log(data.description);
        //console.log('sdp:  ' + data.sender + '   to:' + data.to);
        socket.to(data.to).emit('sdp', data);
    });

    //candidates 消息的转发
    socket.on('ice candidates', (data) => {
        // console.log('ice candidates:  ');
        // console.log(data);
        socket.to(data.to).emit('ice candidates', data);
    });

    // 发送所有在线用户的id到新用户
    socket.emit("get current users", [...onlineUsers]);
});

server.listen(16386);